package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.ClubCardBean;
import com.ukao.steward.bean.SearchUserBean;
import com.ukao.steward.bean.VipCardListBean;
import com.ukao.steward.bean.addressBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PickerViewDialog;
import com.ukao.steward.eventbus.ReadCardEvent;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.listener.OnLocationListener;
import com.ukao.steward.pesenter.valetRunners.TransactVipPesenter;
import com.ukao.steward.ui.valetRunners.storeCreatOrder.StoreClientInfoFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.LocationUtils;
import com.ukao.steward.util.MyDateUtils;
import com.ukao.steward.util.RegularUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.TransactVipView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


import static com.ukao.steward.R.id.card_level;
import static com.ukao.steward.R.id.detail_district;
import static com.ukao.steward.R.id.left_phone;
import static com.ukao.steward.R.id.save_btn;

/**
 * 办理会员
 */
public class BuildVipFragment extends MvpFragment<TransactVipPesenter> implements TransactVipView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.product_name)
    EditText name;

    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.district)
    TextView district;
    Unbinder unbinder;
    @BindView(left_phone)
    TextView leftPhone;
    @BindView(R.id.left_name)
    TextView leftName;
    @BindView(R.id.left_district)
    TextView leftDistrict;
    @BindView(R.id.card_level)
    TextView cardLevel;
    @BindView(detail_district)
    EditText detailDistrict;
    @BindView(save_btn)
    Button saveBtn;
    @BindView(R.id.detail_district_left)
    TextView detailDistrictLeft;

    @BindView(R.id.cardNumber)
    EditText cardNumber;
    @BindView(R.id.location_image)
    ImageView locationImage;
    @BindView(R.id.left_cardNumber)
    TextView leftCardNumber;
    @BindView(R.id.boy)
    RadioButton boy;
    @BindView(R.id.gail)
    RadioButton gail;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private OptionsPickerView mProvinceDialog;
    private ArrayList<addressBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private ArrayList<ArrayList<ArrayList<String>>> options3Items;
    private List<addressBean> provinceCityLists;
    private List<VipCardListBean> mVipCardData;
    private List<ClubCardBean> mSexData = new ArrayList<>();
    private OptionsPickerView mSexDialog;
    private OptionsPickerView mCardDialog;
    private String keyword;
    public String latitude = "";
    public String longitude = "";
    public String sexId = "0";
    public String regionalId = "";
    public String strBirthday = "";
    public String cardId = "";
    private String strPhone;
    private LocationUtils mLocationUtils;
    public int option1, option2, option3;
    private boolean isStop;
    private String strCardNumber;
    private boolean isStoreCreatOrderEnter;


    public static BuildVipFragment newInstance(String keyword, boolean isStoreCreatOrderEnter) {
        BuildVipFragment fragment = new BuildVipFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, keyword);
        args.putBoolean(ARG_PARAM2, isStoreCreatOrderEnter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            keyword= getArguments().getString(ARG_PARAM1);
            isStoreCreatOrderEnter= getArguments().getBoolean(ARG_PARAM2,false);

        }
    }

    @Override
    protected TransactVipPesenter createPresenter() {
        return new TransactVipPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_transact_vip, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();

    }


    @Override
    protected void initView() {

        mLocationUtils = new LocationUtils(_mActivity, mOnLocationListener);
        mvpPresenter.searchVipCard(false);
        if (RegularUtils.isMobileSimple(keyword)) phone.setText(keyword);
        KeyBoardUtil.showKeyboard(name);
        leftPhone.setText(mustSpanText("手机号"));
        leftName.setText(mustSpanText("姓名"));
        leftCardNumber.setText(mustSpanText("卡号"));
        mvpPresenter.getAddressProvinceData(_mActivity);
        mLocationUtils.startLocation();
        setStatusBarTintColor(R.color.normal_blue);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("办理会员");

        String[] sexArray = getResources().getStringArray(R.array.sex_array);
        String[] sexArrayId = getResources().getStringArray(R.array.sex_id);
        for (int i = 0; i < sexArray.length; i++) {
            ClubCardBean mClubCardBean = new ClubCardBean(sexArray[i], sexArrayId[i]);
            mSexData.add(mClubCardBean);
        }

    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(ReadCardEvent event) {


        switch (event.getMessage()) {
            case READCARD:/*读卡*/
                HashMap mData = (HashMap) event.getData();
                String strCardNumber = (String) mData.get(ARG_PARAM2);
                if (CheckUtils.isEmpty(strCardNumber)) {
                    T.show(getString(R.string.read_card_failure));
                    return;
                } else {
                    Long intCardNumber = Long.parseLong(strCardNumber, 16);
                    cardNumber.setText(intCardNumber + "");


                }


                break;
            case NOSUPPORT:/*手机 不支持*/
                T.show("此手机不支持读卡");
                break;

        }
    }


    private OnLocationListener mOnLocationListener = new OnLocationListener() {


        @Override
        public void OnLocationSucceed(AMapLocation amapLocation) {
            L.i("amapLocation");
            if (!isAdded()) return;
            longitude = String.valueOf(amapLocation.getLongitude());
            latitude = String.valueOf(amapLocation.getLatitude());
            String strProvince = amapLocation.getProvince().replace("省", "");
            String strCity = amapLocation.getCity().replace("市", "");
            String strDistrict = amapLocation.getDistrict();
            regionalId = amapLocation.getAdCode();
            district.setText(strProvince + " " + strCity + " " + strDistrict);
            String address = amapLocation.getAddress();
            try {
                if (!strDistrict.isEmpty()) {
                    String temp = strDistrict.substring(strDistrict.length() - 1, strDistrict.length());
                    int indexOf = address.indexOf(temp);
                    if (indexOf != -1) {
                        String detailAddress = address.substring(indexOf + 1, address.length());
                        detailDistrict.setText(detailAddress);

                    }
                }

            } catch (Exception e) {

            }


//            if (isStop) return;
//            ThreadUtils.runOnBackgroundThread(new Runnable() {
//                @Override
//                public void run() {
//                    for (int i = 0; i < options1Items.size(); i++) {
//                        if (options1Items.get(i).getLabel().equals(strProvince)) {
//                            if (!isStop) {
//                                option1 = i;
//                            }
//
//                        }
//                    }
//                    for (int i = 0; i < options2Items.get(option1).size(); i++) {
//                        String option2Name = options2Items.get(option1).get(i);
//                        if (!isStop) {
//                            if (option2Name.equals(strCity)) {
//                                option2 = i;
//                            }
//                        }
//
//                    }
//                    for (int i = 0; i < options3Items.get(option1).get(option2).size(); i++) {
//                        if (!isStop) {
//                            if (options3Items.get(option2).get(i).equals(strDistrict)) {
//                                option3 = i;
//                            }
//                        }
//
//                    }
//                }
//            });

        }

        @Override
        public void OnLocationFailure(String error) {

        }
    };

    @Override
    protected void initListener() {
        super.initListener();
        // name.addTextChangedListener(mTextWatcher);
        //  phone.addTextChangedListener(mTextWatcher);
        // cardNumber.addTextChangedListener(mTextWatcher);
    }

    private TextWatcher mTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            isSaveGo();

        }
    };

    private void isSaveGo() {
        String strphone = getText(phone);
        String strname = getText(name);
        String strcardNumber = getText(cardNumber);

        if (strphone.isEmpty() || strname.isEmpty()) {
            if (saveBtn.isEnabled()) {
                saveBtn.setAlpha(0.5f);
                saveBtn.setEnabled(false);
            }

        } else if (!saveBtn.isEnabled()) {
            saveBtn.setAlpha(1f);
            saveBtn.setEnabled(true);
        }
    }


    @OnClick({R.id.back_btn, card_level, R.id.birthday, R.id.district, save_btn, R.id.location_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.location_image:
                mLocationUtils.startLocation();
                isStop = true;
                break;
            case save_btn:
                strPhone = getText(phone);
                String strName = getText(name);
                strCardNumber = getText(cardNumber);
                String strdistrict = getText(district);
                String strdetailDistrict = getText(detailDistrict);
                if (strPhone.isEmpty() && strCardNumber.isEmpty()) {
                    T.show("手机号或卡号任填一项");
                    return;
                } else if (strName.isEmpty()) {
                    T.show("姓名");
                    return;
                }

                HashMap mHashMap = new HashMap<String, String>();
                mHashMap.put("accessToken", SaveParams.getToken());
                if (!CheckUtils.isEmpty(strPhone)) {
                    mHashMap.put("phone", strPhone);
                }
                if (!CheckUtils.isEmpty(strCardNumber)) {
                    mHashMap.put("cardNo", strCardNumber);
                }
                mHashMap.put("name", strName);


                    mHashMap.put("sex",boy.isChecked()?"1":"2");

                if (!CheckUtils.isEmpty(cardId)) {
                    mHashMap.put("cardId", cardId);
                }
                if (!CheckUtils.isEmpty(regionalId)) {
                    mHashMap.put("regionalId", regionalId);/*区域id*/
                }
                mHashMap.put("regionalDesc", strdistrict);/*省市区描述*/
                mHashMap.put("detail", strdetailDistrict);/*详细地址*/
                if (!CheckUtils.isEmpty(strBirthday)) {
                    mHashMap.put("birthday", strBirthday);
                }
                if (!CheckUtils.isEmpty(latitude)) {
                    mHashMap.put("latitude", latitude);/*精度*/
                }
                if (!CheckUtils.isEmpty(longitude)) {
                    mHashMap.put("longitude", longitude);/*纬度*/
                }
                L.i("mHashMap=" + mHashMap.toString());
                mvpPresenter.addUserInfo(mHashMap);


                break;
            case R.id.back_btn:
                finish();
                break;
//            case R.id.sex:
//                KeyBoardUtil.hideKeyboard(_mActivity);
//                if (CheckUtils.isNull(mSexDialog)) {
//                    mSexDialog = PickerViewDialog.getInstance().ShowCityPickerView(_mActivity, getString(R.string.sex), mOnOptionsSelectListener);
//                    mSexDialog.setPicker(mSexData);
//                    mSexDialog.show(sex);
//                } else {
//                    mSexDialog.show(sex);
//                }
//
//
//                break;
            case card_level:
                KeyBoardUtil.hideKeyboard(_mActivity);
                if (CheckUtils.isNull(mVipCardData)) {
                    mvpPresenter.searchVipCard(true);
                    return;
                }
                showCardLevelDialog();


                break;
            case R.id.birthday:
                String strbirthday = birthday.getText().toString();
                PickerViewDialog.getInstance().showDatePicker(strbirthday, Constant.TIME_TYPE, _mActivity, mOnTimeSelectListener);
                break;
            case R.id.district:
                KeyBoardUtil.hideKeyboard(_mActivity);
                ShowCityPickerView();


                break;


        }
    }

    private void ShowCityPickerView() {
        try {
            if (mProvinceDialog == null) {
                mProvinceDialog = PickerViewDialog.getInstance().
                        ShowCityPickerViewDe(_mActivity, getString(R.string.city_selection), mOnOptionsSelectListener, option1, option2, option3);
                mProvinceDialog.setPicker(options1Items, options2Items, options3Items);//三级选择器
                mProvinceDialog.show(district);
            } else {
                mProvinceDialog.show(district);

            }
        } catch (Exception e) {

            mProvinceDialog = null;

        }

    }

    private void showCardLevelDialog() {
        if (CheckUtils.isNull(mCardDialog)) {
            mCardDialog = PickerViewDialog.getInstance().ShowCityPickerView(_mActivity, getString(R.string.vip_card), mOnOptionsSelectListener);
            mCardDialog.setPicker(mVipCardData);
            mCardDialog.show(cardLevel);
        } else {

            mCardDialog.show(cardLevel);
        }
    }

    private OptionsPickerView.OnOptionsSelectListener mOnOptionsSelectListener = new OptionsPickerView.OnOptionsSelectListener() {


        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            switch (v.getId()) {
                case R.id.sex:
//                    ClubCardBean mSexItem = mSexData.get(options1);
//                    sexId = mSexItem.getSexId();
//                    sex.setText(mSexItem.getPickerViewText());
                    break;
                case R.id.card_level:
                    VipCardListBean mmVipItem = mVipCardData.get(options1);
                    cardId = String.valueOf(mmVipItem.getId());
                    cardLevel.setText(mmVipItem.getPickerViewText());
                    break;
                case R.id.district:
                    //返回的分别是三个级别的选中位置
                    String tx = options1Items.get(options1).getPickerViewText() + " " +
                            options2Items.get(options1).get(options2) + " " +
                            options3Items.get(options1).get(options2).get(options3);
                    regionalId = provinceCityLists.get(options1).getChildren().get(options2).getChildren().get(options3).getValue() + "";
                    district.setText(tx);
                    isSaveGo();
                    break;
            }


        }
    };
    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener = new TimePickerView.OnTimeSelectListener() {

        @Override
        public void onTimeSelect(Date date, View v) {
            strBirthday = MyDateUtils.formatDate(date);
            birthday.setText(MyDateUtils.getTime(date, Constant.TIME_TYPE));


        }
    };


    @Override
    public void cityDataSucceed(ArrayList<addressBean> provinceCityLists, ArrayList<addressBean> options1Items, ArrayList<ArrayList<String>> options2Items, ArrayList<ArrayList<ArrayList<String>>> options3Items) {
        this.options1Items = options1Items;
        this.options2Items = options2Items;
        this.options3Items = options3Items;
        this.provinceCityLists = provinceCityLists;
    }

    /**
     * 添加用户成功
     *
     * @param msg
     */
    @Override
    public void addUserInfoSucceed(String msg) {
        T.show("保存成功");
        saveBtn.setVisibility(View.GONE);
        mvpPresenter.queryKeyword(strPhone.isEmpty() ? strCardNumber : strPhone);
    }

    @Override
    public void vipCardSucceed(List<VipCardListBean> mVipCardData, final boolean ishowDialog) {
        this.mVipCardData = mVipCardData;
        if (ishowDialog)
            showCardLevelDialog();
    }


    /**
     * 查询用户
     *
     * @param mSearchUserBean 用户信息
     */
    @Override
    public void queryKeyword(final SearchUserBean mSearchUserBean) {
        popTo(BuildVipFragment.class, true, new Runnable() {
            @Override
            public void run() {
                if (isStoreCreatOrderEnter){
                    start(StoreClientInfoFragment.newInstance(mSearchUserBean,""), SINGLETASK);

                }else{
                    start(GuestFragment.newInstance(mSearchUserBean, ""), SINGLETASK);
                }



            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        isStop = true;
        if (mLocationUtils != null) {
            mLocationUtils.destroyLocation();
        }

    }
}
